Given two non-negative integers, num1 and num2 represented as string, return the sum of num1 and num2 as a string.
You must solve the problem without using any built-in library for handling large integers (such as BigInteger). You must also not convert the inputs to integers directly.
切記題目不可使用 int() 直接對input進行轉換!!
不使用int() 獲得integers的方法:使用ord()將字元轉為ASCII,再將結果和ord('0')相減,即可得到int(字元)
使用上述方法獲得各個integer
因為字串會由最大位元數開始讀取,所以我們設定一個result,設定其初值為零,
下一次recursive時,會乘上十倍,即往前一位數
class Solution:
def addStrings(self, num1: str, num2: str) -> str:
result1 = 0
result2 = 0
for i in num1:
result1 = 10*result1 + ord(i) - ord('0')
for j in num2:
result2 = 10*result2 + ord(j) - ord('0')
return str(result1+result2)
後來發現也可以使用function,這樣可以免於寫兩次一樣的東西
class Solution:
def addStrings(self, num1: str, num2: str) -> str:
def str2int(num):
result = 0
for i in num:
result = 10*result + ord(i) - ord('0')
return result
return str(str2int(num1)+str2int(num2))
本來今天還想寫 706. Design HashMap,目前尚在理解self用法(很菜啦哈哈哈)